<template>
  <div class="main-container" style="min-height: 600px">
    <el-row style="margin-top: 100px;">
      <el-col :offset="4" :span="2" style=" width: 120px;">
        <div class="avatar-wrapper">
          <img :src="userInfo.avatar"/>
        </div>
      </el-col>
      <el-col :span="13" :offset="1">
        <div class="nickname-wrapper">
          <span v-if="!nicknameEdit">{{ userInfo.nickname }}</span>
          <el-button v-if="!nicknameEdit" type="text" icon="el-icon-edit" style="margin-left:5px" @click="handleNicknameEdit"/>
          <el-form v-if="nicknameEdit" ref="userForm" :model="userForm" :rules="userRules" @submit.native.prevent>
            <el-input  ref="nicknameInput" placeholder="请输入昵称" v-model="userForm.nickname" prop="nickname" class="nickname-input" @keyup.enter.native="submitNickname" @blur="cancel">
              <el-button icon="el-icon-check" slot="append" @click="submitNickname"></el-button>
            </el-input>
          </el-form>
        </div>
        <div class="username-wrapper">UID:{{ userInfo.username }}</div>
        <div>
          <el-button type="text" @click="handleLogOut">退出登录</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :offset="4" :span="16">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="我的订单" name="order">
            <el-table :data="orderList">
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-table :data="props.row.prodList" border>
                    <el-table-column label="产品名称" prop="title"></el-table-column>
                    <el-table-column label="产品介绍" prop="img">
                      <template slot-scope="scope">
                        <img :src="scope.row.img" style="width:100px"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="单价" prop="price"></el-table-column>
                    <el-table-column label="数量" prop="amount"></el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column label="订单号" prop="order_id"/>
              <el-table-column label="收件人" prop="name"/>
              <el-table-column label="手机号" prop="phone_number"/>
              <el-table-column label="订单金额" prop="price"/>
              <el-table-column label="详细地址" prop="address"/>
              <el-table-column label="状态" prop="status">
                <template slot-scope="scope">
                  <span v-if="scope.row.status === 0">未付款</span>
                  <span v-if="scope.row.status === 1">代发货</span>
                  <span v-if="scope.row.status === 2">已发货</span>
                  <span v-if="scope.row.status === 3">已完成</span>
                  <span v-if="scope.row.status === 4">已取消</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" prop="create_time"/>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    v-if="scope.row.status === 0"
                    @click="handleOrderPay(scope.row)"
                  >继续付款</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    v-if="scope.row.status === 0"
                    @click="handleOrderCancel(scope.row)"
                  >取消</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    v-if="scope.row.status === 2"
                    @click="handleOrderFinish(scope.row)"
                  >确认收货</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="收货地址" name="address">
            <el-row>
              <el-col :span="2">
                <el-button icon="el-icon-plus" size="mini" @click="handleAddAddr">添加</el-button>
              </el-col>
            </el-row>
            <el-table :data="addrList">
              <el-table-column label="收件人" prop="name"/>
              <el-table-column label="手机号" prop="phone_number"/>
              <el-table-column label="详细地址" prop="address">
                <template slot-scope="scope">
                  <span>{{ scope.row.address }}</span>
                  <el-tag v-if="scope.row.is_default === 1" size="mini" type="warning" effect="dark">默认</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                  size="mini"
                  type="text"
                  @click="handleUpdateAddr(scope.row)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteAddr(scope.row)"
                  v-if="scope.row.is_default !== 1"
                >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    
    <el-dialog :title="title" :visible.sync="openAddrDialog">
      <el-form ref="addrForm" :model="addrForm" :rules="addrRules" label-width="80px">
        <el-form-item label="收件人" prop="name">
          <el-input v-model="addrForm.name" placeholder="请输入收件人名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone_number">
          <el-input v-model="addrForm.phone_number" placeholder="请输入收件人手机号" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addrForm.address" type="textarea" placeholder="请输入详细地址"  :autosize="{ minRows: 3, maxRows: 5}" maxlength="100" show-word-limit/>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addrForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitAddrForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="支付" :visible.sync="openPayDialog" @close="handlePaid">
      <img style="margin: auto;display: block;" :src="pay.qrcode"/>
      <div style="text-align: center;font-size: 40px;font-weight: bold;color: #065b2b;">{{ pay.price }} ¥</div>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { getInfo, update } from '@/api/user'
import { listAddr, addAddr, getAddr, updateAddr, deleteAddr } from '@/api/addr'
import { listOrder, payOrder, paidOrder, cancelOrder, finishOrder } from '@/api/order'

export default {
  name: 'User',
  data() {
    return {
      title: null,
      addrList: [],
      orderList: [],
      openAddrDialog: false,
      nicknameEdit: false,
      activeName: 'order',
      userInfo: {},
      userForm: {},
      userRules: {
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
      },
      addrForm: {},
      addrRules: {},
      openPayDialog: false,
      pay: {}
    }
  },
  created() {
    this.getUserInfo()
    this.getAddrList()
    this.getOrderList()
  },
  methods: {
    getUserInfo() {
      getInfo().then(res => {
        this.userInfo = res.data
      })
    },
    getOrderList() {
      listOrder().then(res => {
        this.orderList = res.data
      })
    },
    getAddrList() {
      listAddr().then(res => {
        this.addrList = res.data
      })
    },
    handleAddAddr() {
      
      AMap.plugin('AMap.CitySearch', function () {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          console.log('status: ', status)
          console.log('result: ', result)
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            const province = result.province
            const city = result.city
          }
        })
      })

      this.addrForm = {
        addr_id: null,
        name: null,
        address: null,
        phone_number: null,
        isDefault: false,
      }
      this.title = '添加收货地址'
      this.openAddrDialog = true
    },
    handleUpdateAddr(addr) {
      const addr_id = addr.addr_id
      getAddr(addr_id).then(res => {
        this.addrForm = res.data
        this.title = '修改收货地址'
        this.openAddrDialog = true
      })
    },
    handleDeleteAddr(addr) {
      const addr_id = addr.addr_id
      this.$confirm('是否确认删除', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAddr(addr_id).then(res => {
          if (res.code === 200) {
              this.$message({
              message: "删除成功",
              type: 'success',
              duration: 1000
            })
            this.getAddrList()
          }
        })
      }).catch(() => {});
    },
    handleTabClick(tab, event) {

    },
    handleNicknameEdit() {
      const nickname = this.userInfo.nickname
      this.userForm = {
        nickname: nickname,
      }
      this.nicknameEdit = true
      // DOM加载需要时间，延迟聚焦
      setTimeout(()=>{
        this.$refs.nicknameInput.focus()
      }, 0)
    },
    cancel() {
      // this.userForm = {}
      if (this.userInfo.nickname === this.userForm.nickname) {
        // 未修改，取消
        this.nicknameEdit = false
      }
    },
    submitNickname() {
      console.log(this.userForm)
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          update(this.userForm).then(res => {
            if (res.code === 200) {
              this.$message({
                message: "修改成功",
                type: 'success',
                duration: 1000
              })
              this.nicknameEdit = false
              this.userInfo.nickname = this.userForm.nickname
            } else {
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 1000
              })
            }
          })
        }
      })
    },
    submitAddrForm() {
      this.$refs["addrForm"].validate(valid => {
        if (valid) {
          if (this.addrForm.addr_id != null) {
            updateAddr(this.addrForm).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: "修改成功",
                  type: 'success',
                  duration: 1000
                })
                this.openAddrDialog = false
                this.getAddrList()
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error',
                  duration: 1000
                })
              }
            })
          } else {
            addAddr(this.addrForm).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: "添加成功",
                  type: 'success',
                  duration: 1000
                })
                this.openAddrDialog = false
                this.getAddrList()
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error',
                  duration: 1000
                })
              }
            })
          }
        }
      })
    },
    handleOrderPay(order) {
      const order_id = order.order_id
      payOrder(order_id).then(res => {
        if (res.code === 200) {
          this.pay = res.data
          this.openPayDialog = true
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            duration: 1000
          })
        }
      })
    },
    handleOrderCancel(order) {
      const order_id = order.order_id
      this.$confirm('是否确认取消订单', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelOrder(order_id).then(res => {
        this.getOrderList()
      })
      }).catch(() => {});
    },
    handlePaid() {
      this.$confirm('是否已完成支付', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paidOrder(this.pay.order_id).then(res => {
          this.getOrderList()
        })
      }).catch(() => {});
    },
    handleOrderFinish(order) {
      const order_id = order.order_id
      this.$confirm('是否确认收到货物', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        finishOrder(order_id).then(res => {
        this.getOrderList()
      })
      }).catch(() => {});
    },
    handleLogOut() {
      this.$confirm('是否确认退出登录', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Cookies.remove('token');
        const protocol = window.location.protocol
        const host = window.location.host
        const href = protocol + '//' + host + '/'
        window.location.href = href
      }).catch(() => {});
    },
  },
}
</script>

<style>
.avatar-wrapper {
  position: relative;
  display: inline-block;
  height: 120px;
  text-align: center;
}
/* .avatar-wrapper:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 120px;
  border-radius: 50%;
} */
.nickname-wrapper {
  height: 55px;
  font-size: 40px;
}
.nickname-input {
  width: 100%; 
  font-size: 40px;
}
.nickname-wrapper .el-input {
  width:  100%;
  
}
.nickname-wrapper .el-input .el-input__inner {
  padding: 0;
  height: 44px;
}
.nickname-input .el-input-group__append {
  font-size: 20px;
  height: 40px !important;
  /* background-color: red; */
}
.username-wrapper {
  font-size: 20px;
  color: #999;
}
.avatar-wrapper img {
  width: 120px;
  height: 120px;
  text-align: center;
  border-radius: 50%
}
</style>
